//
//  SJView.m
//  CWeekly
//
//  Created by Tiger on 12-4-12.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SJView.h"
#import "AppDelegate.h"
#import "ZipArchive.h"
#import <QuartzCore/QuartzCore.h>
#define HEIGHT_S 1024-75-58
#define HEIGHT_H 768-75-58

@implementation SJView

- (void)dealloc
{
    [table release];
    [bookList release];
    [queue release];
    [loadingDic release];
    [super dealloc];
}

- (id)initWithH:(BOOL)isH
{
    self = [super init];
    if (self) {
        // Initialization code
        
        [[NSNotificationCenter defaultCenter] addObserver: self 
												 selector: @selector(reflashShujiaTable) 
													 name: @"ReflashShujiaTable" 
												   object: nil ];
        
        [[NSNotificationCenter defaultCenter] addObserver: self 
												 selector: @selector(cancelDownload) 
													 name: @"CancelDownload" 
												   object: nil ];
        
        _isH = isH;
        
        queue = [[ASINetworkQueue alloc] init];
        //[queue reset];
        queue.maxConcurrentOperationCount = 1;
        queue.shouldCancelAllRequestsOnFailure = NO;
        [queue setShowAccurateProgress:YES];//高精度进度
        [queue go];
        
        bookList = [[NSMutableArray alloc]init];
        loadingDic = [[NSMutableDictionary alloc]init];
        AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
        if ([[appDelegate getShujiaList] count]>0) {
            [bookList addObjectsFromArray:[appDelegate getShujiaList]];
        }
        
        totalCount = [bookList count];
        
        table = [[UITableView alloc]init];
        table.allowsSelection = NO;
        table.delegate = self;
        table.dataSource = self;
        table.backgroundColor = [UIColor clearColor];
        table.separatorStyle=UITableViewCellSeparatorStyleNone;
        [self addSubview:table];
        
        if (_isH) {
            self.frame = CGRectMake(0, 55, 1024, HEIGHT_H);
            table.frame = CGRectMake(0, 0, 1024, HEIGHT_H);
            columnCount = 3;
        }
        else {
            self.frame = CGRectMake(0, 55, 768, HEIGHT_S);
            table.frame = CGRectMake(0, 0, 768, HEIGHT_S);
            columnCount = 2;
        }
    }
    return self;
}

- (void)reflashShujiaTable
{
    [bookList removeAllObjects];
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    if ([[appDelegate getShujiaList] count]>0) {
        [bookList addObjectsFromArray:[appDelegate getShujiaList]];
    }
    
    [table reloadData];
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        self.frame = CGRectMake(0, 55, 1024, HEIGHT_H);
        table.frame = CGRectMake(0, 0, 1024, HEIGHT_H);
        _isH = YES;
    }
    else {  
        self.frame = CGRectMake(0, 55, 768, HEIGHT_S);
        table.frame = CGRectMake(0, 0, 768, HEIGHT_S);
        _isH = NO;
    }
    
    [table reloadData];
}

#pragma mark - 
#pragma mark UITableViewDatasource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 240;
}

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
	if (_isH) {
        columnCount = 3;
    }
    else {
        columnCount = 2;
    }
    
    NSInteger rowCount = ceil((CGFloat)[bookList count]/(CGFloat)columnCount);
    
    if (_isH) {
        if (rowCount<3) {
            rowCount = 3;
        }
    }
    else {
        if (rowCount<4) {
            rowCount = 4;
        }
    }
    
    return rowCount;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	
	static NSString* ListIdentifier = @"ListIdentifier";
	UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:ListIdentifier];
	
	if (cell == nil)
	{
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ListIdentifier];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;  //去掉选中时的颜色
	}
	
	for (UIView* subView in [cell.contentView subviews])
	{
		[subView removeFromSuperview];
	}
	
	for (int i=0; i<columnCount; i++) {
        NSInteger index = indexPath.row*columnCount+i;
        
        if (index < [bookList count]) {
            
            CGFloat pb = 50;
            CGFloat width = (table.frame.size.width - pb*2) / columnCount;
            
            CGFloat x = (width - 238)/2;
            
            UIImageView *book = [[UIImageView alloc]initWithFrame:CGRectMake(width*i+x+pb, 30, 128, 160)];
            book.tag = 15000+index;
            book.layer.borderColor=[[UIColor blackColor] colorWithAlphaComponent:0.6].CGColor;
            book.layer.borderWidth=2;
            book.layer.shadowOffset = CGSizeMake(2, 2);
            book.layer.shadowRadius = 1.0;
            book.layer.shadowColor = [UIColor blackColor].CGColor;
            book.layer.shadowOpacity = 0.8;
            book.image=[UIImage imageNamed:@"smallloading_v.png"];
            [cell.contentView addSubview:book];
            [book release];
            
            NSDictionary *dic = [bookList objectAtIndex:index];
            NSString *strUrl = [NSString stringWithFormat:IMAGE_URL,[dic objectForKey:@"mgImg"]];
            
            ImageDownloader *imageDownloader = [[ImageDownloader alloc]initWithUrl:strUrl index:index];
            imageDownloader.delegate = self;
            UIImage *image = [imageDownloader getImage];
            if (nil == image) {
                image = [UIImage imageNamed:@"smallloading_v.png"];//默认图片
                [bufferList addObject:imageDownloader];
            }
            [imageDownloader release];
            book.image = image;
            
            UIButton* readBtn=[UIButton buttonWithType:UIButtonTypeCustom];
            readBtn.enabled = NO;
            [readBtn setImage:[UIImage imageNamed:@"read.png"] forState:UIControlStateNormal];
            readBtn.tag = 10000+index;
            [readBtn addTarget:self action:@selector(btnEvent:) forControlEvents:UIControlEventTouchUpInside];
            readBtn.frame=CGRectMake(width*i+x+148+pb-4, 30, 63, 30);
            [cell.contentView addSubview:readBtn];
            [cell bringSubviewToFront:readBtn];

            NSString* mgPeriod = [[dic objectForKey:@"mgPeriod"] stringByReplacingOccurrencesOfString:@"+" withString:@"\n"];
            NSString* mgIssue = [[[dic objectForKey:@"mgIssue"] substringFromIndex:5] stringByReplacingOccurrencesOfString:@"-" withString:@"月"];
            
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(width*i+x+148+pb, 30+30+10, 100, 80)];
            label.text = [NSString stringWithFormat:@"%@\n%@出版\n总第%@期",mgPeriod,mgIssue,[dic objectForKey:@"mgTotal"]];
            label.numberOfLines = 4;
            label.font = [UIFont systemFontOfSize:16.0];
            label.backgroundColor = [UIColor clearColor];
            label.textColor = [UIColor whiteColor];
            [cell.contentView addSubview:label];
            [label release];
            [cell bringSubviewToFront:label];

            
            UIButton* deleteBtn=[UIButton buttonWithType:UIButtonTypeCustom];
            deleteBtn.tag = 5000+index;
            [deleteBtn addTarget:self action:@selector(btnEvent:) forControlEvents:UIControlEventTouchUpInside];
            [deleteBtn setImage:[UIImage imageNamed:@"delete.png"] forState:UIControlStateNormal];
            deleteBtn.frame=CGRectMake(width*i+x+148+pb-4, 190-30, 63, 30);
            [cell.contentView addSubview:deleteBtn];
            [cell bringSubviewToFront:deleteBtn];
            
            UIProgressView *progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(width*i+x+pb, 210, 128, 20)];
            progressView.tag = 1000+index;
            progressView.progress = 0.0;
            //progressView.hidden = YES;
            [cell.contentView addSubview:progressView];
            [progressView release];
            
            NSString *contentLength = @"";
            
            if ([[bookList objectAtIndex:index] objectForKey:@"contentLength"]) {
                contentLength = [[bookList objectAtIndex:index] objectForKey:@"contentLength"];
            }
            
            UILabel *progressLabel = [[UILabel alloc]initWithFrame:CGRectMake(140, -5, 200, 20)];
            progressLabel.tag = 999;
            progressLabel.text = @"正在等待...";
            progressLabel.textColor = [UIColor whiteColor];
            progressLabel.backgroundColor = [UIColor clearColor];
            progressLabel.font = [UIFont systemFontOfSize:14.0];
            [progressView addSubview:progressLabel];
            [progressLabel release];
            
            NSString *mgId = [NSString stringWithFormat:@"%@",[[bookList objectAtIndex:index] objectForKey:@"mgId"]];
            NSString *rootPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/BookData"];
            NSString *bookPath = [rootPath stringByAppendingPathComponent:mgId];
            
            if ([[NSFileManager defaultManager] fileExistsAtPath:bookPath]) {
                readBtn.enabled = YES;
                progressView.hidden = YES;
            }
            else {
                if (![loadingDic objectForKey:mgId]) {
                    [loadingDic setObject:@"Loading" forKey:mgId];
                    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/TempData"];
                    NSString *zipPath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip",mgId]];
                    NSString *tempPath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.temp",mgId]];
                    
                    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@HttpDownload?mgid=%@",SERVER,[[bookList objectAtIndex:index] objectForKey:@"mgId"]]];
                    
                    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
                    request.tag = index;
                    //[request setDownloadProgressDelegate:progressView];
                    request.delegate = self;//代理
                    [request setDownloadDestinationPath:zipPath];//下载路径
                    [request setTemporaryFileDownloadPath:tempPath];//缓存路径
                    [request setAllowResumeForFileDownloads:YES];//断点续传
                    request.downloadProgressDelegate = self;//下载进度代理
                    [queue addOperation:request];//添加到队列，队列启动后不需重新启动
                }
            }

        }
    }
    
    UIImageView*bracket=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bracket.png"]];
    //CGSize size=cell.contentView.frame.size;
    
    if (_isH) {
        bracket.frame=CGRectMake(20, 239-60, 1024-40, 85);
    }
    else {
        bracket.frame=CGRectMake(20, 239-60, 768-40, 85);
    }
    
    [cell.contentView addSubview:bracket];
    [cell.contentView sendSubviewToBack:bracket];
    [bracket release];
	
	cell.backgroundColor = [UIColor clearColor];
	
	return cell;
}

- (void)cancelDownloadImage
{
	[bufferList makeObjectsPerformSelector:@selector(cancel)];
}

- (void)imageDidFinishLoad:(UIImage *)image index:(NSInteger)index
{
	if (image) {
        if (_isH) {
            columnCount = 3;
        }
        else {
            columnCount = 2;
        }
        
		NSInteger row = index/columnCount;
        UITableViewCell *cell = (UITableViewCell *)[table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];
        
        UIImageView *imageView = (UIImageView *)[cell viewWithTag:15000+index];
		imageView.image = image;
	}
}

- (void)deleteFile:(NSInteger)index
{
    if (index < [bookList count]) {
        
        [self cancelDownload];
        
        NSString *mgId = [NSString stringWithFormat:@"%@",[[bookList objectAtIndex:index] objectForKey:@"mgId"]];
        NSString *rootPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/BookData"];
        NSString *bookPath = [rootPath stringByAppendingPathComponent:mgId];
        
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/TempData"];
        NSString *zipPath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip",mgId]];
        NSString *tempPath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.temp",mgId]];
        
        BOOL clear = YES;
        if ([[NSFileManager defaultManager] fileExistsAtPath:zipPath]) {
            if ([[NSFileManager defaultManager] removeItemAtPath:zipPath error:nil]) {
                NSLog(@"删除压缩文件");
            }
            else {
                NSLog(@"删除压缩文件失败");
                clear = NO;
            }
        }
        if ([[NSFileManager defaultManager] fileExistsAtPath:tempPath]) {
            if ([[NSFileManager defaultManager] removeItemAtPath:tempPath error:nil]) {
                NSLog(@"删除临时文件");
            }
            else {
                NSLog(@"删除临时文件失败");
                clear = NO;
            }
        }
        if ([[NSFileManager defaultManager] fileExistsAtPath:bookPath]) {
            if ([[NSFileManager defaultManager] removeItemAtPath:bookPath error:nil]) {
                NSLog(@"删除文件夹");
            }
            else {
                NSLog(@"删除文件夹失败");
                clear = NO;
            }
        }
        if (clear) {
            
        }
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ReflashShangdianList" object: nil];
}

- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders
{
    NSInteger index = request.tag;
    currentLoading = request.tag;
    
    NSMutableDictionary *book = [[NSMutableDictionary alloc]initWithDictionary:[bookList objectAtIndex:index]];
    
    if (![book objectForKey:@"contentLength"]) {
        NSString *contentLength = [NSString stringWithFormat:@"%.1fM",request.contentLength/1024.0/1024.0];
        [book setValue:contentLength forKey:@"contentLength"];
        
        [bookList removeObjectAtIndex:index];
        [bookList insertObject:book atIndex:index];
        
        AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
        [appDelegate setShujiaList:bookList];
    }
    
    [book release];
    
    //[table reloadData];
}

- (void)setProgress:(float)newProgress
{
    NSInteger row;
    if (_isH) {
        row = floor((CGFloat)currentLoading / 3.0);
    }
    else {
        row = floor((CGFloat)currentLoading / 2.0);
    }
    
    UITableViewCell *cell = [table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];
    UIProgressView *progressView = (UIProgressView *)[cell viewWithTag:currentLoading+1000];
    UILabel *progressLabel = (UILabel *)[progressView viewWithTag:999];
    
    NSString *contentLength = [[bookList objectAtIndex:currentLoading] objectForKey:@"contentLength"];
    progressView.progress = newProgress;
    progressLabel.text = [NSString stringWithFormat:@"%.1f%%  共%@",newProgress*100,contentLength];
}

- (void)requestStarted:(ASIHTTPRequest *)request
{
    //
}

- (void)cancelDownload
{
    for (int i=0; i<[[queue operations] count]; i++) {
        ASIHTTPRequest *request = [[queue operations] objectAtIndex:i];
        [request clearDelegatesAndCancel];
    }
    [loadingDic removeAllObjects];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSLog(@"下载完成！");
    
    NSString *mgId = [NSString stringWithFormat:@"%@",[[bookList objectAtIndex:request.tag] objectForKey:@"mgId"]];
    [loadingDic removeObjectForKey:mgId];
    [self unzipFile:mgId];
    
    [table reloadData];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ReflashShangdianList" object: nil];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSInteger index = request.tag;
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle: nil 
                                                   message: @"下载失败" 
                                                  delegate: self 
                                         cancelButtonTitle: @"确定" 
                                         otherButtonTitles: nil];
    [alert show];
    [alert release];
    
    NSInteger row;
    if (_isH) {
        row = floor((CGFloat)currentLoading / 3.0);
    }
    else {
        row = floor((CGFloat)currentLoading / 2.0);
    }
    
    NSString *mgId = [NSString stringWithFormat:@"%@",[[bookList objectAtIndex:request.tag] objectForKey:@"mgId"]];
    [loadingDic removeObjectForKey:mgId];
    
    UITableViewCell *cell = [table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];
    UIProgressView *progressView = (UIProgressView *)[cell viewWithTag:index+1000];
    [progressView removeFromSuperview];
    
    [self deleteFile:index];
    [bookList removeObjectAtIndex:index];
    [table reloadData];
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    [appDelegate setShujiaList:bookList];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ReflashShangdianList" object: nil];
}

- (void)btnEvent:(UIButton *)sender
{
    if (sender.tag>=5000 && sender.tag<10000) {
        NSInteger index = sender.tag - 5000;
        [self deleteFile:index];
        [bookList removeObjectAtIndex:index];
        [table reloadData];
        AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
        [appDelegate setShujiaList:bookList];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ReflashShoucangList" object: nil];
    }
    else {
        NSInteger index=sender.tag-10000;
        NSDictionary* book=[bookList objectAtIndex:index];
        NSMutableDictionary *object = [NSMutableDictionary dictionary];
        [object setValue:[book valueForKey:@"mgId"] forKey:@"mgId"];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"ToDetaiViewController" object:object];
    }
}

- (void)unzipFile:(NSString *)mgId
{
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/BookData"];
    NSString *unzipPath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",mgId]];
    
    NSString *tempPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/TempData"];
    NSString *zipPath = [tempPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip",mgId]];
    
    ZipArchive *unzip = [[ZipArchive alloc] init];
    if ([unzip UnzipOpenFile:zipPath]) {
        BOOL result = [unzip UnzipFileTo:unzipPath overWrite:YES];
        if (result) {
            NSLog(@"解压成功");
        }
        else {
            NSLog(@"解压失败");
        }
        [unzip UnzipCloseFile];
    }
    else {
        NSLog(@"未找到压缩文件");
    }
    [unzip release];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:zipPath]) {
        if ([[NSFileManager defaultManager] removeItemAtPath:zipPath error:nil]) {
            NSLog(@"删除压缩文件");
        }
        else {
            NSLog(@"删除压缩文件失败");
        }
    }
}

@end
